package com.example;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 服务端启动类
 *
 * @author: 李涛
 * @version: 2020年07月31日 10:55
 */
@SpringBootApplication
@ControllerAdvice
@EnableEurekaClient
@EnableHystrix
@RestController
public class ProductApplicaiton {

	@Value("${server.port}")
	private String port;

	@Autowired
	private Environment env;

	public static void main(String[] args) {
		SpringApplication.run(ProductApplicaiton.class, args);
	}

	@GetMapping("/hello")
	/**
	 * 配置参考HystrixPropertiesManager
	 */
	@HystrixCommand(
			commandKey = "product-hello",
			groupKey = "product",
			// 方法如果有异常先进入这里，然后进入ControllerAdvice
			fallbackMethod = "noHello",
			commandProperties = {
					@HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "10"),
					@HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "THREAD"),
					@HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "1000")
			},
			threadPoolKey = "product-hello-thread-pool"

	)
	public ResponseEntity<String> hello() {
		System.out.println("hello-"+Thread.currentThread().getName());
		return ResponseEntity.ok("hello World Server port " + port + "!");
	}

	public ResponseEntity<String> noHello() {
		System.out.println("no-hello-"+Thread.currentThread().getName());
		return ResponseEntity.ok("no hello World Server port " + port + "!");
	}

	@GetMapping("/config")
	public ResponseEntity<String> config() {
		return ResponseEntity.ok("config is " + env.getProperty("config-mark.username") + "!");
	}

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public ResponseEntity<String> handleException(Exception e) {
		System.out.println("advice-hello-"+Thread.currentThread().getName());
		return ResponseEntity.ok("controller-advice hello World Server port " + port + "!" + e.getMessage());
	}
}
